/*java jdk 1.7+
# -*- coding: utf-8 -
'''
Created on 2020年05月10日
@author: zxyong 13738196011
'''*/

package com.zxy.common;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.json.JSONArray;
import org.json.JSONObject;

public class Com_Fun
{
	//通用调试函数
	public static void debug_in(Exception e,String strClass)
	{
		if(strClass.indexOf("@") != -1)
			strClass = strClass.substring(0,strClass.indexOf("@"));
		StackTraceElement traceElement = null;		
		for(StackTraceElement temElement : e.getStackTrace()){
			if(temElement.toString().indexOf(strClass) == 0){
				traceElement = temElement;
				break;
			}
		}
		if(java.util.Objects.equals(traceElement,null)) 
			traceElement = e.getStackTrace()[0];
		String _File_ = traceElement.getClassName();
		String _FUNC_ = traceElement.getMethodName();
		int _LINE_ = traceElement.getLineNumber();
		StringBuilder excStr = new StringBuilder();
		excStr.append(Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss") + "=>" + _File_
				+ "=>" + _FUNC_ + "=>" + String.valueOf(_LINE_) + "=>"
				+ e.getMessage()+"=>error:"+strClass);
		com.zxy.adminlog.UsAdmin_Log uL = new com.zxy.adminlog.UsAdmin_Log(Com_Para.ApplicationPath,excStr,"exception");
		try
		{
			uL.WriteLog();
			System.out.println(excStr.toString());
		}
		catch(IOException e1)
		{
		}
	}

	//通用调试函数
	public static void debug_in(Exception e, String strClass,String strMsg)
	{
		if(strClass.indexOf("@") != -1)
			strClass = strClass.substring(0,strClass.indexOf("@"));
		StackTraceElement traceElement = null;		
		for(StackTraceElement temElement : e.getStackTrace()){
			if(temElement.toString().indexOf(strClass) == 0){
				traceElement = temElement;
				break;
			}
		}
		if(java.util.Objects.equals(traceElement,null)) 
			traceElement = e.getStackTrace()[0];
		String _File_ = traceElement.getClassName();
		String _FUNC_ = traceElement.getMethodName();
		int _LINE_ = traceElement.getLineNumber();
		StringBuilder excStr = new StringBuilder();
		excStr.append(Com_Fun.DateTimeStr("yyyy-MM-dd HH:mm:ss") + "=>" + _File_
				+ "=>" + _FUNC_ + "=>" + String.valueOf(_LINE_) + "=>"
				+ e.getMessage() + "=>info:" + strMsg);
		com.zxy.adminlog.UsAdmin_Log uL = new com.zxy.adminlog.UsAdmin_Log(Com_Para.ApplicationPath,excStr,"exception");
		try
		{
			uL.WriteLog();
			System.out.println(excStr.toString());
		}
		catch(IOException e1)
		{
		}
	}

	//编码格式转换
	public static char[] ChartsetChange(char[] chars,String OldChartset,String NewChartset){
		byte[] byts = Com_Fun.getBytes(chars,OldChartset);
		char[] chrs = Com_Fun.getChars(byts,NewChartset);
		return chrs;
	}
	
	//char[]转byte[]
	public static byte[] getBytes(char[] chars,String charset)
	{
		Charset cs = Charset.forName(charset);
		CharBuffer cb = CharBuffer.allocate(chars.length);
		cb.put(chars);
		cb.flip();
		ByteBuffer bb = cs.encode(cb);
		return bb.array();
	}

	//byte[] 转char[]
	public static char[] getChars(byte[] bytes,String charset)
	{
		Charset cs = Charset.forName(charset);
		ByteBuffer bb = ByteBuffer.allocate(bytes.length);
		bb.put(bytes).flip();
		CharBuffer cb = cs.decode(bb);
		return cb.array();
	}
	
	//返回数据结果 json格式字符串
	public static String get_ope_result(String param_name,String strResult,String strError_Desc){
		String strValue = "";
		strValue = "{\"" + param_name + "\":[{\""
				+ Com_Fun.getLowUpp("s_result") + "\":\""+strResult+"\",\""
				+ Com_Fun.getLowUpp("error_desc") + "\":\""+Com_Fun.s_encode(strError_Desc)+"\"}]}";
		return strValue;
	}
	
	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return String
	 */
	public static String parseHexStr2Byte(String hex)
	{
		String result = "";
		for(int i = 0;i < hex.length();i++)
		{
			String hexStr = hex.substring(i,i + 1);
			String bin = Integer.toBinaryString(Integer.valueOf(hexStr,16));
			for(int j = bin.length();j < 4;j++)
			{
				bin = "0" + bin;
			}
			result = result + bin;
		}
		return result;
	}

	// 16进制转10进制
	public static String convertHexToString(String hex)
	{
		StringBuilder sb = new StringBuilder();
		StringBuilder temp = new StringBuilder();
		for(int i = 0;i < hex.length() - 1;i += 2)
		{
			String output = hex.substring(i,(i + 2));
			int decimal = Integer.parseInt(output,16);
			sb.append((char) decimal);
			temp.append(decimal);
		}

		return temp.toString();
	}

	// 16进制转10进制ascii
	public static String convertHexToascii(String hex)
	{
		StringBuilder sb = new StringBuilder();
		StringBuilder temp = new StringBuilder();
		for(int i = 0;i < hex.length() - 1;i += 2)
		{
			String output = hex.substring(i,(i + 2));
			if(output.equals("00"))
			{
				sb.append("0");
				temp.append(0);
			}else
			{
				int decimal = Integer.parseInt(output,16);
				sb.append((char) decimal);
				temp.append(decimal);
			}
		}

		return sb.toString();
	}

	// 微信后台数据发送
	public static String SendDataServer(String strValue)
	{
		String result = "";
		OutputStream out = null;
		BufferedReader in = null;
		try
		{
			URL realUrl = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			conn.setUseCaches(false);
			conn.setRequestProperty("accept","*/*");
			conn.setRequestProperty("connection","close");
			conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("content-type","application/x-www-form-urlencoded");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = conn.getOutputStream();
			out.write(strValue.getBytes(Com_Para.U_CODE));
			out.flush();
			int resultCode = conn.getResponseCode();
			if(HttpURLConnection.HTTP_OK == resultCode)
			{
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),Com_Para.U_CODE));
				String line;
				while(!java.util.Objects.equals((line = in.readLine()),null))
				{
					result += line;
				}
			}
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
		}
		finally
		{
			try
			{
				if(!java.util.Objects.equals(in,null))
				{
					in.close();
				}
				if(!java.util.Objects.equals(out,null))
				{
					out.close();
				}
			}
			catch(IOException ex)
			{

			}
		}
		return result;
	}

	// ResultSet转JSON,char字段需要url编码
	public static JSONArray ResultSetToJSONCom(ResultSet rs) throws Exception
	{
		// json数组
		JSONArray array = new JSONArray();
		// 获取列数
		ResultSetMetaData metaData = rs.getMetaData();
		int columnCount = metaData.getColumnCount();
		// 遍历ResultSet中的每条数据
		while(rs.next())
		{
			JSONObject jsonObj = new JSONObject(new LinkedHashMap());
			// 遍历每一列
			for(int i = 1;i <= columnCount;i++)
			{
				String columnName = "";
				if(Com_Para.iReturnUppLower == 1)
					columnName = metaData.getColumnLabel(i).toUpperCase();
				else if(Com_Para.iReturnUppLower == 2)
					columnName = metaData.getColumnLabel(i).toLowerCase();
				else
					columnName = metaData.getColumnLabel(i);
				int iType = metaData.getColumnType(i);
				String value = Com_Fun.NoNull(rs.getString(columnName));
				
				if((iType == java.sql.Types.VARCHAR
					|| iType == java.sql.Types.NVARCHAR 
					|| iType == java.sql.Types.CHAR  
					|| iType == java.sql.Types.NCHAR
					|| iType == java.sql.Types.CLOB 
					|| iType == java.sql.Types.NCLOB
					|| iType == java.sql.Types.LONGVARCHAR)
					&& !java.util.Objects.equals(value,"")
				)
				{
					value = s_encode(value);
				}
				jsonObj.put(columnName,value);
			}
			array.put(jsonObj);
		}
		return array;
	}
		
	// ResultSet转JSON
	public static JSONArray ResultSetToJSON(ResultSet rs) throws Exception
	{
		// json数组
		JSONArray array = new JSONArray();
		// 获取列数
		ResultSetMetaData metaData = rs.getMetaData();
		int columnCount = metaData.getColumnCount();
		// 遍历ResultSet中的每条数据
		while(rs.next())
		{
			JSONObject jsonObj = new JSONObject(new LinkedHashMap());
			// 遍历每一列
			for(int i = 1;i <= columnCount;i++)
			{
				String columnName = "";
				if(Com_Para.iReturnUppLower == 1)
					columnName = metaData.getColumnLabel(i).toUpperCase();
				else if(Com_Para.iReturnUppLower == 2)
					columnName = metaData.getColumnLabel(i).toLowerCase();
				else
					columnName = metaData.getColumnLabel(i);
				
//				String columnName = metaData.getColumnLabel(i);
				String value = Com_Fun.NoNull(rs.getString(columnName));
				jsonObj.put(columnName,value);
			}
			array.put(jsonObj);
		}
		return array;
	}

	public static String Http_Post(String url_path, String strCon)
	{
		// if(url_path.indexOf("https:") == 0)
		// return Com_Fun.Https_Post(url_path,strCon);
		String strResult = "";
		OutputStream out = null;
		BufferedReader in = null;
		HttpURLConnection conn = null;
		try
		{
			URL realUrl = new URL(url_path);
			conn = (HttpURLConnection) realUrl.openConnection();
			conn.setRequestProperty("accept","*/*");
			conn.setRequestProperty("connection","Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
			// conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible;
			// MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("content-type","text/html;charset=UTF-8");
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = conn.getOutputStream();
			out.write(strCon.getBytes("UTF-8"));
			out.flush();
			int resultCode = conn.getResponseCode();
			if(HttpURLConnection.HTTP_OK == resultCode)
			{
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				String line;
				while(!java.util.Objects.equals((line = in.readLine()),null))
				{
					strResult += line;
				}
			}
		}
		catch(Exception e)
		{
			return strResult = "error:" + e.getMessage();
		}
		finally
		{
			try
			{
				if(!java.util.Objects.equals(out,null))
				{
					out.close();
				}
				if(!java.util.Objects.equals(in,null))
				{
					in.close();
				}
				conn.disconnect();
			}
			catch(IOException ex)
			{
			}
		}
		return strResult;
	}

	// 创建文件并写入信息
	public static void SaveFileData(String strTFileName, String strContent)
	{
		File fiFile = null;
		FileWriter sw = null;
		try
		{
			fiFile = new File(strTFileName);
			if(!fiFile.exists())
			{
				fiFile.createNewFile();
				sw = new FileWriter(strTFileName,false);
				sw.write(strContent);
				sw.close();
			}else
			{
				sw = new FileWriter(strTFileName,false);
				sw.write("");
				sw.flush();
				sw.write(strContent);
				sw.close();
			}
		}
		catch(Exception en)
		{

		}
	}

	public static String ZipFiles(String sourPath, String targetPathFile) throws Exception
	{
		// 创建zip输出流
		ZipOutputStream out = null;
		// 创建缓冲输出流
		BufferedOutputStream bos = null;
		File sourceFile = null;
		out = new ZipOutputStream(new FileOutputStream(targetPathFile));
		// bos = new BufferedOutputStream(out);
		sourceFile = new File(sourPath);
		// 调用函数
		compress(out,sourceFile,sourceFile.getName());
		out.close();
		return targetPathFile;
	}

	public static void compress(ZipOutputStream out, File sourceFile, String base) throws Exception
	{
		// 如果路径为目录（文件夹）
		if(sourceFile.isDirectory())
		{
			// 取出文件夹中的文件（或子文件夹）
			File[] flist = sourceFile.listFiles();

			if(flist.length == 0)
			// 如果文件夹为空，则只需在目的地zip文件中写入一个目录进入点
			{
				out.putNextEntry(new ZipEntry(base + "/"));
			}else
			// 如果文件夹不为空，则递归调用compress，文件夹中的每一个文件（或文件夹）进行压缩
			{
				for(int i = 0;i < flist.length;i++)
				{
					compress(out,flist[i],base + "/" + flist[i].getName());
				}
			}
		}else
		// 如果不是目录（文件夹），即为文件，则先写入目录进入点，之后将文件写入zip文件中
		{
			FileInputStream fos = new FileInputStream(sourceFile);
			// BufferedInputStream bis = new BufferedInputStream(fos);
			out.putNextEntry(new ZipEntry(base));
			int tag;
			// 将源文件写入到zip文件中
			while((tag = fos.read()) != -1)
			{
				out.write(tag);
			}
			fos.close();
		}
	}

	public static void unZipFiles(String zipPath, String descDir) throws Exception
	{
		unZipFiles(new File(zipPath),descDir);
	}

	public static void unZipFiles(File zipFile, String descDir) throws Exception
	{
		File pathFile = new File(descDir);
		if(!pathFile.exists())
		{
			pathFile.mkdirs();
		}
		ZipFile zip = new ZipFile(zipFile);
		for(Enumeration entries = zip.entries();entries.hasMoreElements();)
		{
			try
			{
				ZipEntry entry = (ZipEntry) entries.nextElement();
				String zipEntryName = entry.getName();
				InputStream in = zip.getInputStream(entry);
				String outPath = (descDir + zipEntryName).replace("\\*","/");
				// 判断路径是否存在,不存在则创建文件路径
				File file = new File(outPath.substring(0,outPath.lastIndexOf('/')));
				if(!file.exists())
				{
					file.mkdirs();
				}
				// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
				if(new File(outPath).isDirectory())
				{
					continue;
				}
				// 输出文件路径信息
				OutputStream out = new FileOutputStream(outPath);
				byte[] buf1 = new byte[1024];
				int len;
				while((len = in.read(buf1)) > 0)
				{
					out.write(buf1,0,len);
				}
				in.close();
				out.close();
			}
			catch(Exception e)
			{
				Com_Fun.debug_in(e,Com_Fun.class.toString());
			}
		}
	}

	public static void deleteDirWihtFile(File dir)
	{
		if(dir.isFile())
			dir.delete();
		if(java.util.Objects.equals(dir,null) || !dir.exists()
				|| !dir.isDirectory())
			return;
		for(File file: dir.listFiles())
		{
			if(file.isFile())
				file.delete();
			// 删除所有文件
			else if(file.isDirectory())
				deleteDirWihtFile(file);
			// 递规的方式删除文件夹
		}
		dir.delete();
		// 删除目录本身
	}

	public static String Https_Post_test(String url_path, String strCon)
	{
		HttpsURLConnection.setDefaultHostnameVerifier(new Post_SSL().new NullHostNameVerifier());
		SSLContext sc;
		try
		{
			sc = SSLContext.getInstance("TLS");
			sc.init(null,Post_SSL.trustAllCerts,new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
		}

		String strResult = "";
		OutputStream out = null;
		BufferedReader in = null;
		HttpsURLConnection conn = null;
		try
		{
			URL realUrl = new URL(url_path);
			conn = (HttpsURLConnection) realUrl.openConnection();
			conn.setRequestProperty("accept","*/*");
			conn.setRequestProperty("x-esso-project-id","A00001");
			conn.setRequestProperty("x-esso-signature","B00001");
			conn.setRequestProperty("connection","Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
			// conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible;
			// MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("content-type","text/html;charset=UTF-8");
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = conn.getOutputStream();
			out.write(strCon.getBytes("UTF-8"));
			out.flush();
			int resultCode = conn.getResponseCode();
			if(HttpURLConnection.HTTP_OK == resultCode)
			{
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				String line;
				while(!java.util.Objects.equals((line = in.readLine()),null))
				{
					strResult += line;
				}
			}
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
			return strResult = "error:" + e.getMessage();
		}
		finally
		{
			try
			{
				if(!java.util.Objects.equals(out,null))
				{
					out.close();
				}
				if(!java.util.Objects.equals(in,null))
				{
					in.close();
				}
				conn.disconnect();
			}
			catch(IOException ex)
			{
			}
		}
		return strResult;
	}

	public static String Https_Post(String url_path, String strCon)
	{
		HttpsURLConnection.setDefaultHostnameVerifier(new Post_SSL().new NullHostNameVerifier());
		SSLContext sc;
		try
		{
			sc = SSLContext.getInstance("TLS");
			sc.init(null,Post_SSL.trustAllCerts,new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
		}

		String strResult = "";
		OutputStream out = null;
		BufferedReader in = null;
		HttpsURLConnection conn = null;
		try
		{
			URL realUrl = new URL(url_path);
			conn = (HttpsURLConnection) realUrl.openConnection();
			conn.setRequestProperty("accept","*/*");
			conn.setRequestProperty("connection","Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
			// conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible;
			// MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("content-type","text/html;charset=UTF-8");
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = conn.getOutputStream();
			out.write(strCon.getBytes("UTF-8"));
			out.flush();
			int resultCode = conn.getResponseCode();
			if(HttpURLConnection.HTTP_OK == resultCode)
			{
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				String line;
				while(!java.util.Objects.equals((line = in.readLine()),null))
				{
					strResult += line;
				}
			}
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
			return strResult = "error:" + e.getMessage();
		}
		finally
		{
			try
			{
				if(!java.util.Objects.equals(out,null))
				{
					out.close();
				}
				if(!java.util.Objects.equals(in,null))
				{
					in.close();
				}
				conn.disconnect();
			}
			catch(IOException ex)
			{
			}
		}
		return strResult;
	}

	public static StringBuilder readVueFile(String filePath)
	{
		StringBuilder strResult = new StringBuilder();
		try
		{
			File file = new File(filePath);
			if(file.isFile() && file.exists())
			{ // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file),Com_Para.U_CODE);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while(!java.util.Objects.equals((lineTxt = bufferedReader.readLine()),null))
				{
					String strTemV = lineTxt.replace("\\$","\\\"").replace("\"","\\\"").replace("\t","").replace("\n","").replace("\r","");// .replace("\\$","\\\\\\\"").replace("\"","\\\\\\\"");
					strResult.append(strTemV);// .replace("\"","\\\"").replace("$","\\\""));//.replace("\t","").replace("\n","").replace("\r","").replace("\"","\\\"").replace("$","\""));
				}
				read.close();
			}else
			{
				String strError = "<div class=\"middle-box text-center animated fadeInDown\"><h1>404</h1><h3 class=\"font-bold\">页面未找到！</h3><div class=\"error-desc\">抱歉，页面好像去火星了~</div></div>";
				String strTemV = strError.replace("\\$","\\\"").replace("\"","\\\"").replace("\t","").replace("\n","").replace("\r","");
				strResult.append(strTemV);
			}
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
		}
		return strResult;
	}

	public static String readTxtFile(String filePath)
	{
		String strResult = "";
		try
		{
			File file = new File(filePath);
			if(file.isFile() && file.exists())
			{ // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file),Com_Para.U_CODE);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while(!java.util.Objects.equals((lineTxt = bufferedReader.readLine()),null))
				{
					strResult += lineTxt + "\r\n";
				}
				read.close();
			}else
			{
				strResult = "";
			}
		}
		catch(Exception e)
		{
			strResult = "";
		}
		return strResult;
	}

	public static String getLowUpp(String inputValue)
	{
		if(Com_Para.iReturnUppLower == 1)
			return inputValue.toUpperCase();
		else if(Com_Para.iReturnUppLower == 2)
			return inputValue.toLowerCase();
		else
			return inputValue;
	}

	public static String getParam_value1(String param_value1)
	{
		String strResult = "";
		try
		{
			String strGRT = "";
			if(param_value1.length() > 64)
			{
				strGRT = URLDecoder.decode(param_value1,"UTF-8");
				if(strGRT.length() == 64)
					strResult = com.zxy.common.EncodeUtil.aesDecrypt(strGRT,com.zxy.common.EncodeUtil.key);
				else
					strResult = param_value1;
			}else if(param_value1.length() == 64)
			{
				strResult = com.zxy.common.EncodeUtil.aesDecrypt(param_value1,com.zxy.common.EncodeUtil.key);
			}else
				strResult = param_value1;
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
			strResult = param_value1;
		}
		return strResult;
	}

	public static String setSconnections()
	{
		String strResult = "";
		try
		{
			strResult = com.zxy.common.EncodeUtil.aesEncrypt("1VZPMMIR00LTCAKGJI28GCGOGNYXO96G"
					+ String.valueOf(new Date().getTime())
					+ "bq052@a5zgk2fj%4@02mht&pmcf#%*ep",com.zxy.common.EncodeUtil.key);
		}
		catch(Exception es)
		{
		}
		return strResult;
	}

	public static boolean flagSconnections()
	{
		return true;
		// if(Com_Para.strSessionAva.equals(""))
		// return false;
		// String strF = getSconnections(Com_Para.strSessionAva);
		// long lgAva = Long.valueOf(strF.substring(32,45));
		// long lgTime = new Date().getTime() - lgAva;
		// long lgS = 365 * 24 * 60 * 60 * 1000L;
		// // 有效期365天
		// if(lgTime < lgS)
		// return true;
		// else return false;
	}

	public static Object getFieldValueByName(String fieldName, Object o) throws Exception
	{
		String firstLetter = fieldName.substring(0,1).toUpperCase();
		String getter = "get" + firstLetter + fieldName.substring(1);
		Method method = o.getClass().getMethod(getter,new Class[] {});
		Object value = method.invoke(o,new Object[] {});
		if(!java.util.Objects.equals(value,null)
				&& java.util.Objects.equals(value.getClass().getName(),"java.util.Date"))
			value = Com_Fun.DateTimeToStr((Date) value,"yyyy-MM-dd HH:mm:ss");
		return value;
	}

	public static String getSconnections(String encValue)
	{
		String strResult = "";
		try
		{
			strResult = com.zxy.common.EncodeUtil.aesDecrypt(encValue,com.zxy.common.EncodeUtil.key);
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
		}
		return strResult;
	}

	public static int get_maxConnections(String strDriverCode)
	{
		if(strDriverCode.equals("org.sqlite.JDBC"))
			return 10;
		else
			return 30;
	}

	public static String NoNull(Object objTag)
	{
		if(java.util.Objects.equals(objTag,null))
			return "";
		else
			return objTag.toString().trim();
	}

	public static int ZeroNull(Object objTag)
	{
		if(java.util.Objects.equals(objTag,null))
			return 0;
		else
			return Integer.valueOf(objTag.toString());
	}

	// 根据session_id获取用户信息
	public static String GetSessionInfo(String session_id)
	{
		String strResult = "";
		if(!java.util.Objects.equals(Com_Para.htSession,null))
		{
			for(Map.Entry<String, Object[]> entry: Com_Para.htSession.entrySet())
			{
				Object[] objV = entry.getValue();
				if(entry.getKey().equals(session_id))
				{
					strResult = objV[0].toString();
					break;
				}
			}
		}
		return strResult;
	}

	public static String FloatToStr(float finput)
	{
		java.math.BigDecimal bg = new java.math.BigDecimal(finput);
		return bg.toString();
	}

	public static String ReplacePath(String loginName, String strValue, int iFlag, int IS_URLENCODE)
	{
		String strResult = strValue;
		if(iFlag == 1)
		{
			String strG = strValue.replace("src='","src='"
					+ Com_Para.HTTP_Path).replace("src=\"","src=\'"
							+ Com_Para.HTTP_Path).replace("\"","'");
			if(strG.length() > 3)
			{
				String strAtt = strG.substring(strG.length() - 4,strG.length());
				if(strAtt.toLowerCase().equals(".jpg")
						|| strAtt.toLowerCase().equals(".gif")
						|| strAtt.toLowerCase().equals(".png")
						|| strAtt.toLowerCase().equals(".bmp"))
				{
					strG = Com_Para.HTTP_Path + loginName + "/" + strG;
				}
			}
			strResult = strG;
		}
		if(IS_URLENCODE == 1)
		{
			try
			{
				strResult = s_encode(strResult);
			}
			catch(Exception e)
			{
			}
		}
		return strResult;
	}

	// 加密
	public static String DecData(String strInput)
	{
		return strInput;
	}

	// 解密
	public static String EscData(String strInput)
	{
		return strInput;
	}

	public static String Get_New_GUID()
	{
		return java.util.UUID.randomUUID().toString().toUpperCase();
	}

	public static float Get_dot_two(float fInput)
	{
		return (float) (Math.round(fInput * 100) / 100);
	}

	public static double nextDouble(final double min, final double max)
	{
		return min + ((max - min) * new Random().nextDouble());
	}

	public static int nextInt(final int min, final int max)
	{
		int num = min + (int) (Math.random() * (max - min + 1));
		return num;
	}

	public static int nextIntIndex(final int min, final int max)
	{
		int num = min + (int) (Math.random() * (max - min));
		return num;
	}

	public static double nextInt()
	{
		int iR = Math.abs(new Random().nextInt() % 2);
		return (double) iR;
	}

	public static float Get_dot_two(String fInput)
	{
		return (float) (Math.round(Float.valueOf(fInput) * 100) / 100);
	}

	public static String DateTimeStr(String DateFormat)
	{
		return new SimpleDateFormat(DateFormat).format(new Date());
	}

	public static String DateTimeStrYYYYMMDDHHmmss(String strInput, String DateFormat)
	{
		SimpleDateFormat df = new SimpleDateFormat(DateFormat);
		Date dtREQ_TIME;
		try
		{
			if(java.util.Objects.equals(strInput,""))
				return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			dtREQ_TIME = df.parse(strInput);
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dtREQ_TIME);
		}
		catch(ParseException e)
		{
			return "1900-01-01 00:00:00";
		}
	}

	public static String DateTimeToStr(Date dtREQ_TIME)
	{
		try
		{
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dtREQ_TIME);
		}
		catch(Exception e)
		{
			return "1900-01-01 00:00:00";
		}
	}

	public static String DateTimeToStr(Date dtREQ_TIME, String DateFormat)
	{
		return new SimpleDateFormat(DateFormat).format(dtREQ_TIME);
	}

	public static Date StrDateTime(String DateFormat, String strInput)
	{
		Date dts = null;
		try
		{
			dts = new SimpleDateFormat(DateFormat).parse(strInput);
		}
		catch(ParseException e)
		{
		}
		return dts;
	}

	public static int DateSub(String DateBegin, String DateEnd) throws Exception
	{
		Date dtB = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateBegin);
		Date dtE = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(DateEnd);
		long B = dtB.getTime();
		long E = dtE.getTime();
		int iResult = (int) ((E - B) / 1000);
		return iResult;
	}

	// 月份相加
	public static String stepMonth(String DateFormat, Date sourceDate, int month) throws Exception
	{
		Calendar c = Calendar.getInstance();
		c.setTime(sourceDate);
		c.add(Calendar.MONTH,month);
		return new SimpleDateFormat(DateFormat).format(c.getTime());
	}
	
	// 日份相加
	public static String stepDay(String DateFormat, Date sourceDate, int date)
	{
		Calendar c = Calendar.getInstance();
		c.setTime(sourceDate);
		c.add(Calendar.DATE,date);
		return new SimpleDateFormat(DateFormat).format(c.getTime());
	}
	
	// 小时相加
	public static String stepHour(String DateFormat, Date sourceDate, int hours) throws Exception
	{
		Calendar c = Calendar.getInstance();
		c.setTime(sourceDate);
		c.add(Calendar.HOUR,hours);
		return new SimpleDateFormat(DateFormat).format(c.getTime());
	}

	// 分钟数相加
	public static String stepMinute(String DateFormat, Date sourceDate, int minutes) throws Exception
	{
		Calendar c = Calendar.getInstance();
		c.setTime(sourceDate);
		c.add(Calendar.MINUTE,minutes);
		return new SimpleDateFormat(DateFormat).format(c.getTime());
	}
		
	// 秒数相加
	public static String stepSeconds(String DateFormat, Date sourceDate, int seconds) throws Exception
	{
		Calendar c = Calendar.getInstance();
		c.setTime(sourceDate);
		c.add(Calendar.SECOND,seconds);
		return new SimpleDateFormat(DateFormat).format(c.getTime());
	}

	public static String get0X01()
	{
		byte b1[] =
		{ 0x01 };
		String str1 = new String(b1);
		return str1;
	}

	public static String get0X02()
	{
		byte b2[] =
		{ 0x02 };
		String str2 = new String(b2);
		return str2;
	}

	public static String GetHashTable2(LinkedHashMap<String, String> ht, String key)
	{
		String strResult = "";
		if(java.util.Objects.equals(ht.get(key),null))
			strResult = "";
		else
			strResult = ht.get(key).toString();
		return strResult;
	}
	
	public static String GetHashTable(Hashtable<String, String> ht, String key)
	{
		String strResult = "";
		if(java.util.Objects.equals(ht.get(key),null))
			strResult = "";
		else
			strResult = ht.get(key).toString();
		return strResult;
	}

	//字节数组转16进制
	public String byte2hex(byte[] b)
	{
		String hs = "";
		String stmp = "";
		for(int n = 0;n < b.length;n++)
		{
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if(stmp.length() == 1)
			{
				hs = hs + "0" + stmp;
			}else
			{
				hs = hs + stmp;
			}
		}
		return hs.toUpperCase();
	}

	//16进制转字节数组，未验证
	public byte[] hex2byte(String hex)
	{
		byte[] ret = new byte[8];
		byte[] tmp = hex.getBytes();
		for(int i = 0;i < tmp.length / 2;i++)
		{
			ret[i] = uniteBytes(tmp[i * 2],tmp[i * 2 + 1]);
		}
		return ret;
	}

	//16进制单精度浮点数
	public static float hex2float(String hexString) {
		float fRec = Float.intBitsToFloat(new BigInteger(hexString,16).intValue());
		return fRec;
	}
	
	public byte uniteBytes(byte src0, byte src1)
	{
		byte _b0 = Byte.decode("0x" + new String(new byte[]
		{ src0 })).byteValue();
		_b0 = (byte) (_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[]
		{ src1 })).byteValue();
		byte ret = (byte) (_b0 ^ _b1);
		return ret;
	}

	//高低位转浮点数
	public static float ReadFloat(int n1, int n2, boolean reverse)
	{	
        String n = Integer.toHexString(n1);
        String m = Integer.toHexString(n2);
        String v = "";
        if(reverse)
            v = n + m;
        else
            v = m + n;
        float y =  Com_Fun.hex2float(v);
        return y;
	}
	
	public static JSONObject xmlToJSON(String xml)
	{
		JSONObject obj = new JSONObject(new LinkedHashMap());
		try
		{
			InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
			SAXBuilder sb = new SAXBuilder();
			Document doc = sb.build(is);
			Element root = doc.getRootElement();
			Map<String, Object> map = iterateElement(root);
			obj.put(root.getName(),map);
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
		}
		return obj;
	}

	/**
	 * json转xml
	 */
	public static String JSONToXml(String json, String param_name)
	{
		XMLSerializer xmlSerializer = new XMLSerializer();
		xmlSerializer.setRootName(param_name);
		// xmlSerializer.setObjectName(param_name);
		// xmlSerializer.setArrayName(param_name);
		// xmlSerializer.setSkipNamespaces(true);
		// xmlSerializer.setSkipWhitespace(true);
		xmlSerializer.setTypeHintsEnabled(true);
		String xml = xmlSerializer.write(JSONSerializer.toJSON(json),Com_Para.U_CODE);
		return xml;
	}

	private static Map<String, Object> iterateElement(Element root)
	{
		List childrenList = root.getChildren();
		Element element = null;
		Map map = new HashMap();
		List list = null;
		for(int i = 0;i < childrenList.size();i++)
		{
			list = new ArrayList();
			element = (Element) childrenList.get(i);
			if(element.getChildren().size() > 0)
			{
				if(root.getChildren(element.getName()).size() > 1)
				{
					if(map.containsKey(element.getName()))
					{
						list = (List) map.get(element.getName());
					}
					list.add(iterateElement(element));
					map.put(element.getName(),list);
				}else
				{
					map.put(element.getName(),iterateElement(element));
				}
			}else
			{
				if(root.getChildren(element.getName()).size() > 1)
				{
					if(map.containsKey(element.getName()))
					{
						list = (List) map.get(element.getName());
					}
					list.add(element.getTextTrim());
					map.put(element.getName(),list);
				}else
				{
					map.put(element.getName(),element.getTextTrim());
				}
			}
		}

		return map;
	}

	//url编码
	public static String s_encode(String strInput)
	{
		String strResult = strInput.replace("%27","'").replace("%21","!").replace("%28","(").replace("%29",")").replace("%7E","~").replace("%0D","");// .replace("+","%20");
		try
		{
			return URLEncoder.encode(strResult,Com_Para.U_CODE);
		}
		catch(Exception e)
		{
			return strResult;
		}
	}
		
	//url编码
//	public static String Java_encode(String strInput)
//	{
//		String strResult = strInput.replace("%27","'").replace("%21","!").replace("%28","(").replace("%29",")").replace("%7E","~").replace("%0D","");// .replace("+","%20");
//		return strResult;
//		// return
//		// strInput.replace("%27","'").replace("%21","!").replace("%28","(").replace("%29",")").replace("%7E","~").replace("%0D","").replace("+","%20");
//	}

	public static String GetAbsPath()
	{
		String strResult = Com_Para.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		int iLength = strResult.lastIndexOf(Com_Para.zxyPath);

		String os = System.getProperty("os.name");
		if(os.toLowerCase().startsWith("win"))
		{
			if(iLength > 0)
				return strResult.substring(1,iLength) + "/";
			else
				return strResult.substring(1,strResult.length()) + "/";
		}else
		{
			if(iLength > 0)
				return strResult.substring(0,iLength) + "/";
			else
				return strResult.substring(0,strResult.length()) + "/";
		}
	}

	public static String GetImgPath(String param_name)
	{
		String strReturn = "";
		if(param_name.equals("A01_APP_select_seller_Pic"))
		{
			strReturn = "temp/admin";
		}else if(param_name.equals("A01_APP_ProductByPID_Sort")
				|| param_name.equals("A01_APP_select_Product_ByMainID")
				|| param_name.equals("A01_APP_Cars")
				|| param_name.equals("A01_APP_Orders")
				|| param_name.equals("A01_APP_Orders_By_ID")
				|| param_name.equals("A01_select_product_hot_parent_id"))
		{
			strReturn = "temp/";
		}
		return strReturn;
	}

	public static boolean GetInterSession(String SQLName)
	{
		if(Com_Para.htInterSession.containsKey(SQLName)
				&& Com_Para.htInterSession.get(SQLName) == 1)
			return true;
		else
			return false;
	}

	public static String SetSession(String temsession_id, String values, String login_id)
	{
		if(login_id.equals("") || temsession_id.equals(""))
			return "";
		Object[] objV =
		{ values, new Date() };

		if(java.util.Objects.equals(Com_Para.htLoginCode,null))
		{
			Com_Para.htLoginCode = new Hashtable<String, String>();
		}
		else if(!java.util.Objects.equals(Com_Fun.GetHashTable(Com_Para.htLoginCode,login_id),""))
		{
			//单一登录，禁止单用户重复登录
			if(Com_Para.single_login == 1
				&& !temsession_id.equals(Com_Fun.GetHashTable(Com_Para.htLoginCode,login_id)))
			{
				//将上一登录用户踢掉
				Com_Para.htSession.remove(Com_Fun.GetHashTable(Com_Para.htLoginCode,login_id));
			}
		}
		//记录最新用户login_id和session_id
		Com_Para.htLoginCode.put(login_id,temsession_id);
		if(java.util.Objects.equals(Com_Para.htSession,null))
		{
			Com_Para.htSession = new Hashtable<String, Object[]>();
			Com_Para.htSession.put(temsession_id,objV);
		}else
		{
			if(values.equals("")
					&& Com_Para.htSession.containsKey(temsession_id))
				objV[0] = ((Object[]) Com_Para.htSession.get(temsession_id))[0];
			Com_Para.htSession.put(temsession_id,objV);
		}
		return temsession_id;
	}

	public static boolean HadSession(String keys, String login_id)
	{
		boolean bResult = false;
		if(java.util.Objects.equals(Com_Para.htSession,null))
		{
			Com_Para.htSession = new Hashtable<String, Object[]>();
		}else if(Com_Para.htSession.containsKey(keys))
		{
			//单一登录，禁止单用户重复登录
			if(Com_Para.single_login == 1
				&& !keys.equals(Com_Fun.GetHashTable(Com_Para.htLoginCode,login_id))){
				Com_Para.htSession.remove(keys);
				return false;
			}
			Object[] objV = Com_Para.htSession.get(keys);
			Date dtSession = null;
			try
			{
				dtSession = (Date) objV[1];
				long lgTime = new Date().getTime() - dtSession.getTime();
				String temMAIN_ID = new JSONObject(objV[0].toString()).getJSONArray("SESSION_INFO").getJSONObject(0).getString(Com_Fun.getLowUpp("LOGIN_ID"));
				if(!java.util.Objects.equals(temMAIN_ID,login_id))
				{
					bResult = false;
				}else if(lgTime < Com_Para.SessionTimeOut * 60000)
				{
					objV[1] = dtSession;
					Com_Para.htSession.put(keys,objV);
					bResult = true;
				}else
				{
					Com_Para.htSession.remove(keys);
					bResult = false;
				}
			}
			catch(Exception e)
			{
			}
		}
		return bResult;
	}

	public static String doc2String(Document doc)
	{
		Format format = Format.getPrettyFormat();
		format.setEncoding("UTF-8");
		XMLOutputter xmlout = new XMLOutputter(format);
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		try
		{
			xmlout.output(doc,bo);
		}
		catch(IOException e)
		{
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return bo.toString();
	}

	public static Document ReadXmlFile(File objF)
	{
		Document doc = null;
		SAXBuilder builder = new SAXBuilder();
		try
		{
			doc = builder.build(objF);
		}
		catch(JDOMException e)
		{
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		catch(IOException e)
		{
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return doc;
	}

	public static Document ReadXmlString(String strXml) throws Exception
	{
		Document doc = null;
		SAXBuilder builder = new SAXBuilder();
		doc = builder.build(new StringReader(strXml));
		return doc;
	}

	public static String strTo16(String s)
	{
		String str = "";
		for(int i = 0;i < s.length();i++)
		{
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch);
			str = str + s4;
		}
		return str;
	}

	//字节转16进制
	public static String byteToHex(byte b)
	{
		String hex = Integer.toHexString(b & 0xFF);
		if(hex.length() < 2)
		{
			hex = "0" + hex;
		}
		return hex;
	}

	//16进制转单个字节
	public static byte hexToByte(String inHex)
	{
		return (byte) Integer.parseInt(inHex,16);
	}

	// length用户要求产生字符串的长度
	public static String getRandomString(int length)
	{
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for(int i = 0;i < length;i++)
		{
			int number = random.nextInt(62);
			sb.append(str.charAt(number));
		}
		return sb.toString();
	}

	/*** * 生成固定长度随机中文 * @param n 中文个数 * @return 中文串 */
	public static String getRandomChineseString(int n)
	{
		String zh_cn = "";
		String str = "";
		// Unicode中汉字所占区域\u4e00-\u9fa5,将4e00和9fa5转为10进制
		int start = Integer.parseInt("4e00",16);
		int end = Integer.parseInt("9fa5",16);
		for(int ic = 0;ic < n;ic++)
		{
			// 随机值
			int code = (new Random()).nextInt(end - start + 1) + start;
			// 转字符
			str = new String(new char[]
			{ (char) code });
			zh_cn = zh_cn + str;
		}
		return zh_cn;
	}

	public static boolean Has_Web_Name(String requestString)
	{
		for(String strTem: Com_Para.web_Name)
		{
			if(requestString.indexOf(strTem) != -1)
				return true;
		}
		return false;
	}

	public static String Get_Web_Name(StringBuilder strUrl)
	{
		for(String strTem: Com_Para.web_Name)
		{
			if(strUrl.indexOf(strTem) != -1)
				return strTem;
		}
		return "";
	}

	// 发送TCP/IP数据 字符串形式发送
	public static void SendSocket(StringBuilder strInput, Socket sc) throws Exception
	{
		com.zxy.adminlog.UsAdmin_Log uL = new com.zxy.adminlog.UsAdmin_Log(Com_Para.ApplicationPath,strInput,"SendBegin");
		uL.WriteLog();
		
		sc.setSendBufferSize(1024 * 20);
		BufferedOutputStream bos = null;
		bos = new BufferedOutputStream(sc.getOutputStream());
		bos.write(strInput.toString().getBytes(Com_Para.U_CODE));
		bos.write("\r\n".getBytes(Com_Para.U_CODE));
		bos.flush();
		Thread.sleep(500);
		
		uL = new com.zxy.adminlog.UsAdmin_Log(Com_Para.ApplicationPath,strInput,"SendEnd");
		uL.WriteLog();
	}

	// 发送TCP/IP数据 字节形式发送
	public static void SendSocket(char[] bytes, Socket sc) throws Exception
	{
		sc.setSendBufferSize(1024);
		PrintWriter writer = null;
		OutputStreamWriter owr = null;
		owr = new OutputStreamWriter(sc.getOutputStream(),Com_Para.U_CODE);
		writer = new PrintWriter(owr);
		writer.write(bytes,0,bytes.length);
		writer.flush();
		Thread.sleep(500);
	}

	// 发布MQTT信息
	public static void publish(MqttTopic topic, MqttMessage message)
	{
		try
		{
			MqttDeliveryToken token = topic.publish(message);
			token.waitForCompletion();
			// System.out.println("message is published completely! " +
			// token.isComplete());
		}
		catch(Exception e)
		{
			Com_Fun.debug_in(e,Com_Fun.class.toString());
		}
	}

	/**
	 * 将数字字符串转化为二进制byte数组
	 * 
	 * @param hex
	 * @return byte[]
	 */
	public static byte[] hexStringToByte(String hex)
	{
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for(int i = 0;i < len;i++)
		{
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4
					| toByte(achar[pos + 1]));
		}
		return result;
	}

	private static byte toByte(char c)
	{
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}

	/**
	 * 将二进制数组转化为16进制字符串
	 * 
	 * @param src
	 * @return String
	 */
	public static String bytesToHexString(byte[] src)
	{
		StringBuilder stringBuilder = new StringBuilder();
		if(java.util.Objects.equals(src,null) || src.length <= 0)
		{
			return null;
		}
		for(int i = 0;i < src.length;i++)
		{

			int v = 0;
			if(i == 1)
				v = (src[i] & 0xFF);
			else
				v = (src[i] & 0xFF);
			String hv = Integer.toHexString(v);
			if(hv.length() < 2)
			{
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	//url解码
	public static String s_decode(String strInput, String SU_CODE)
	{
		if(strInput.equals(""))
			return strInput;
		else{
			try
			{
				String strResult = strInput.replace("%27","'").replace("%21","!").replace("%28","(").replace("%29",")").replace("%7E","~").replace("%0D","");// .replace("+","%20");
				return URLDecoder.decode(strResult,SU_CODE);
			}
			catch(UnsupportedEncodingException e)
			{
				return "";
			}
		}
	}
	
	//url解码
	public static String s_decode(String strInput)
	{
		if(strInput.equals(""))
			return strInput;
		else{
			try
			{
				String strResult = strInput.replace("%27","'").replace("%21","!").replace("%28","(").replace("%29",")").replace("%7E","~").replace("%0D","");// .replace("+","%20");
				return URLDecoder.decode(strResult,Com_Para.U_CODE);
			}
			catch(UnsupportedEncodingException e)
			{
				return "";
			}
		}
	}
		
	public static void sort(String a[])
	{
		for(int i = 0;i < a.length - 1;i++)
		{
			for(int j = i + 1;j < a.length;j++)
			{
				if(a[j].compareTo(a[i]) < 0)
				{
					String temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
		}
	}
	
	 //modbus crc校验
    public static String ModBus_CRC_Check(byte[] byteData)
    {
        byte[] CRC = new byte[2];
        Integer wCrc = 0xFFFF;
        for (int i = 0; i < byteData.length; i++)
        {
            wCrc ^= Integer.valueOf(byteData[i]);
            for (int j = 0; j < 8; j++)
            {
                if ((wCrc & 0x0001) == 1)
                {
                    wCrc >>= 1;
                    wCrc ^= 0xA001;
                }
                else
                {
                    wCrc >>= 1;
                }
            }
        }
        CRC[1] = (byte)((wCrc & 0xFF00) >> 8);
        CRC[0] = (byte)(wCrc & 0x00FF);
        return bytesToHexString(CRC);
    }
    
	//用户登录是否锁定
	public static String login_lock(String login_id,String StrIP){
		String error_desc = "";
		//login参数
		if(Com_Para.htLoginFailure.containsKey(login_id)){
			Object[] obj = Com_Para.htLoginFailure.get(login_id);
			obj[3] = StrIP;
			int iMax = 5;//登录失败最大次数
			int lockT = 20;//锁定时间
			long lgTime = new Date().getTime() - ((Date)(obj[1])).getTime();
			//登录失败少于5次不影响
			if((Integer.valueOf(obj[0].toString())) < iMax){
			}
			else{
				//锁定登录
				if((Integer.valueOf(obj[0].toString())) == 6 && lgTime <= lockT * 60 * 1000){
					error_desc = "禁止登录,账号锁定"+lockT+"分钟,请稍后再试";
				}
			}
		}
		return error_desc;
	}
		
	//用户登录失败安全校验 
	public static String login_failure(String login_id,String StrIP){
		String error_desc = "";
		//login参数
		if(Com_Para.htLoginFailure.containsKey(login_id)){
			Object[] obj = Com_Para.htLoginFailure.get(login_id);
			obj[3] = StrIP;
			int iMax = 5;//登录失败最大次数
			int tMax = 3;//分钟内登录失败次数
			int lockT = 20;//锁定时间
			long lgTime = new Date().getTime() - ((Date)(obj[1])).getTime();
			//登录失败少于5次不影响
			if((Integer.valueOf(obj[0].toString())) < iMax){
				//时间不超过3分钟
				if(lgTime <= tMax * 60 * 1000){
					obj[0] = (Integer.valueOf(obj[0].toString())) + 1;
					Com_Para.htLoginFailure.put(login_id,obj);
					error_desc = "登录失败:"+String.valueOf(obj[0])+"次";
				}
				//超过3分钟，重新计算
				else{
					obj[0] = 1;
					obj[1] = new Date();
					obj[2] = 0;
					Com_Para.htLoginFailure.put(login_id,obj);
					error_desc = "登录失败:"+String.valueOf(obj[0])+"次";
				}
			}
			else{
				//锁定登录
				if((Integer.valueOf(obj[0].toString())) == 6 && lgTime <= (Integer.valueOf(obj[2].toString()))){
					error_desc = "禁止登录,账号锁定"+lockT+"分钟,请稍后再试";
				}
				//时间不超过3分钟,锁定20分钟
				else if(lgTime <= tMax * 60 * 1000){
					obj[0] = (Integer.valueOf(obj[0].toString())) + 1;
					obj[2] = lockT * 60 * 1000;
					Com_Para.htLoginFailure.put(login_id,obj);
					error_desc = "登录失败:"+String.valueOf(obj[0])+"次，账号锁定"+lockT+"分钟";
				}
				else{
					obj[0] = 1;
					obj[1] = new Date();
					obj[2] = 0;
					Com_Para.htLoginFailure.put(login_id,obj);
					error_desc = "登录失败:"+String.valueOf(obj[0])+"次";
				}
			}
		}else{
			//[请求失败次数,第一次失败时间,锁定时间,IP地址]
			Object[] obj = {1,new Date(),0,StrIP};
			Com_Para.htLoginFailure.put(login_id,obj);
			error_desc = "登录失败:"+String.valueOf(obj[0])+"次";
		}
		return error_desc;
	}
}